package com.petsbang.utils;

import java.lang.ref.WeakReference;

import com.petsbang.cache.BitmapCache;
import com.petsbang.vo.TaskParam;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoaderTask extends AsyncTask<TaskParam, Void, Bitmap> {

	private TaskParam param;
	private final WeakReference<ImageView> LinearLayoutReference; // 防止内存溢出

	public ImageLoaderTask(ImageView imageView) {
		LinearLayoutReference = new WeakReference<ImageView>(imageView);
	}

	@Override
	protected Bitmap doInBackground(TaskParam... params) {

		param = params[0];
		return loadImageFile(param.getFilename());
	}

	private Bitmap loadImageFile(final String filename) {
		try {	
			Bitmap bmp = BitmapCache.getInstance().getBitmap(filename);
			return bmp;
		} catch (Exception e) {
			Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
		} 
		return null;
	}

	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}

		if (LinearLayoutReference != null) {
			ImageView imageView = LinearLayoutReference.get();

			if (imageView != null && bitmap != null) {
				imageView.setImageBitmap(bitmap);
			}
		}
	}
}